// 블로그 상세 페이지 — 본문은 RootTaleBlogPost(블록 JSON 렌더러)에 위임,
// 메타데이터는 어드민 SEO 패널(metaJson.seo) 값을 우선 적용.
// slug 변경 시: API가 옛 slug로도 글을 찾아 현재 slug로 응답 → 301 redirect.
import type { Metadata } from "next";
import { notFound, permanentRedirect } from "next/navigation";
import { RootTaleBlogPost } from "@roottale/cms-renderer-next/server";
import { postRedirectPath } from "@roottale/cms-renderer-next/routes";

import { getAllPosts, getPost } from "@/lib/blog";

export const revalidate = 1800;

type Props = { params: Promise<{ slug: string }> };

export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map((p) => ({ slug: p.slug }));
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) return {};
  const seo = post.seo;
  const title = seo?.title || post.title;
  const description = seo?.description || post.description;
  return {
    title,
    description,
    ...(seo?.canonical ? { alternates: { canonical: seo.canonical } } : {}),
    ...(seo?.noindex || seo?.nofollow
      ? { robots: { index: !seo?.noindex, follow: !seo?.nofollow } }
      : {}),
    openGraph: {
      type: "article",
      title,
      description,
      publishedTime: post.date,
      ...(post.image ? { images: [{ url: seo?.ogImage || post.image, alt: title }] } : {}),
    },
  };
}

export default async function PostPage({ params }: Props) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound();
  // 옛 slug 로 들어온 요청 → 현재 slug 로 301 (검색 순위 승계).
  const redirect = postRedirectPath(post, slug);
  if (redirect) permanentRedirect(redirect);

  return (
    <main>
      <RootTaleBlogPost
        apiKey={process.env.ROOTTALE_API_KEY!}
        baseUrl={process.env.ROOTTALE_API_BASE}
        slugOrId={post.id}
      />
    </main>
  );
}
